<template>
  <div class="common-layout">
    <el-container class="full-height-container">
      <el-header>
        <div class="header">
          <div class="logo">美遇校园二手商品交易平台</div>
          <div class="search-bar">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索你想要的商品"
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
          <div class="user-section">
            <div v-if="!isLoggedIn" class="login-section">
              <el-button type="primary" @click="goToLogin">登录</el-button>
              <!-- <el-button type="success" @click="goToRegister">注册</el-button> -->
            </div>
            <div v-else class="user-info">
              <el-dropdown @command="handleUserCommand">
                <span class="el-dropdown-link">
                  {{ userName }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="myProducts">个人中心</el-dropdown-item>
                    <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </el-header>
      <el-main class="flex-main">
        <!-- 展示下单 -->
        <OrderDetailsView
          v-if="showOrder"
          v-bind:product-id="productData"
          ref="orderRef"
          @back="showOrder = false"
        />
        <!-- 显示我的商品页面 -->
        <MyProductsView
          v-if="showMyProducts"
          ref="myProductsRef"
          @back="showMyProducts = false"
        />

        <!-- 显示平台商品列表 -->
        <div v-if="showMyProductsList" class="category-filter">
          <el-scrollbar class="category-scroll">
            <div class="category-list">
              <div
                v-for="category in categories"
                :key="category.id"
                :class="['category-item', { active: selectedCategory === category.id }]"
                @click="selectCategory(category.id)"
              >
                {{ category.name }}
              </div>
            </div>
          </el-scrollbar>
        </div>

        <div v-if="showMyProductsList" class="product-list">
          <div class="product-list-header">
            <div class="sort-options">
              <el-button
                v-for="option in sortOptions"
                :key="option.value"
                :type="selectedSort === option.value ? 'primary' : 'default'"
                @click="changeSort(option.value)"
                size="small"
              >
                {{ option.label }}
              </el-button>
            </div>
          </div>

          <div class="product-grid">
            <div
              v-for="product in productList"
              :key="product.id"
              class="product-card"
              @click="viewProductDetail(product.id)"
            >
              <div class="product-image">
                <img :src="getFullImageUrl(product.homeImage)" :alt="product.title" />
              </div>
              <div class="product-info">
                <div class="product-title">{{ product.title }}</div>
                <div class="product-price">¥{{ product.price }}</div>
                <div class="product-meta">
                  <span class="condition">{{ product.condition }}</span>
                  <span class="seller">{{ product.userNickname }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              layout="prev, pager, next"
              @current-change="handlePageChange"
            />
          </div>

        </div>
        <div class="drawer-container">
          <el-drawer 
            v-model="drawerVisible" 
            title="商品详情" 
            direction="rtl" 
            size="80%"
            :destroy-on-close="true"
          >
            <div v-if="currentProduct" class="product-detail">
              <div class="detail-image">
                <el-carousel
                  height="500px"
                  v-if="currentProduct.image && currentProduct.image.length > 0"
                >
                  <el-carousel-item
                    v-for="(image, index) in currentProduct.image"
                    :key="index"
                  >
                    <img
                      :src="getFullImageUrl(image)"
                      :alt="currentProduct.title"
                      class="carousel-image"
                    />
                  </el-carousel-item>
                </el-carousel>
                <img
                  v-else
                  :src="getFullImageUrl(currentProduct.homeImage)"
                  :alt="currentProduct.title"
                  class="single-image"
                />
              </div>
              <div class="detail-info">
                <h2>商品名称:{{ currentProduct.title }}</h2>
                <div class="detail-price">价格:¥{{ currentProduct.price }}</div>
                <div class="detail-condition">
                  新旧程度:{{ currentProduct.condition }}
                </div>

                <div class="detail-meta">
                  <div class="seller">卖家:{{ currentProduct.userNickname }}</div>
                  <div class="time">发布时间:{{ currentProduct.releaseTime }}</div>
                  <div class="status">状态:{{ currentProduct.status }}</div>
                  <div class="number">库存:{{ currentProduct.number }}</div>
                  <div class="sold">已售:{{ currentProduct.sold }}</div>
                  <div class="detail-description">
                    备注:{{ currentProduct.description }}
                  </div>
                </div>
                <!-- <el-button type="primary" @click="contactSeller">用户留言</el-button> -->
                <el-button  type="primary" @click="buyProduct(currentProduct.id)">立即下单</el-button>
              </div>
            </div>
            <!-- 留言区域 -->
            <div class="review-section">
              <h3>商品留言</h3>
              
              <!-- 添加留言表单 -->
              <div v-if="isLoggedIn" class="review-form">
                <h4>{{ replyTarget ? `回复 ${replyTarget.userNickname}:` : '发表留言' }}</h4>
                <el-input
                  v-model="newReviewContent"
                  type="textarea"
                  placeholder="请输入您的留言..."
                  :rows="3"
                  maxlength="200"
                  show-word-limit
                />
                <div class="form-actions">
                  <el-button 
                    type="primary" 
                    @click="submitReview"
                    :loading="isSubmitting"
                  >
                    {{ replyTarget ? '回复' : '发表留言' }}
                  </el-button>
                  <el-button 
                    v-if="replyTarget" 
                    @click="cancelReply"
                  >
                    取消
                  </el-button>
                </div>
              </div>
              <div v-else class="login-prompt">
                <el-alert
                  title="请登录后发表留言"
                  type="info"
                  show-icon
                  :closable="false"
                  :banner="true"
                />
              </div>
              
              <!-- 留言列表 -->
              <div class="review-list">
                <div v-for="review in reviews" :key="review.id" class="review-item">
                  <div class="review-header">
                    <img 
                      :src="getFullImageUrl(review.userProfilePictureSrc)" 
                      :alt="review.userNickname" 
                      class="review-avatar"
                    />
                    <div class="review-user-info">
                      <div class="review-nickname">{{ review.userNickname }}</div>
                      <div class="review-time">{{ review.createTime }}</div>
                    </div>
                    <div class="review-actions">
                      <el-button 
                        type="primary" 
                        link 
                        size="small" 
                        @click="replyToReview(review)"
                      >
                        回复
                      </el-button>
                    </div>
                  </div>
                  <div class="review-content">{{ review.content }}</div>
                  
                  <!-- 回复列表 -->
                  <div v-if="review.replies && review.replies.length > 0" class="reply-list">
                    <div v-for="reply in review.replies" :key="reply.id" class="reply-item">
                      <div class="reply-header">
                        <img 
                          :src="getFullImageUrl(reply.userProfilePictureSrc)" 
                          :alt="reply.userNickname" 
                          class="reply-avatar"
                        />
                        <div class="reply-user-info">
                          <div class="reply-nickname">{{ reply.userNickname }}</div>
                          <div class="reply-time">{{ reply.createTime }}</div>
                        </div>
                      </div>
                      <div class="reply-content">{{ reply.content }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-drawer>
        </div>
      </el-main>

    </el-container>
    <el-footer class="fixed-footer">长春工业大学人文信息学院-计算机科学与工程学院-计算机科学与技术专业-24031237!!!</el-footer>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { Search, ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import instance from "../../utils/request";

import MyProductsView from "./MyProductsView.vue"; // 添加导入
import OrderDetailsView from "../order/OrderDetailsView.vue";

const router = useRouter();
// 用户登录状态
const isLoggedIn = ref(false);
const userName = ref("");
// 当前选中的排序方式
const selectedSort = ref("time");
// 分页相关
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
// 商品列表
const productList = ref([]);
// 抽屉可见性
const drawerVisible = ref(false);
// 当前查看的商品
const currentProduct = ref(null);
// 新增留言内容
const newReviewContent = ref("");
// 留言列表
const reviews = ref([]);
// 提交留言状态
const isSubmitting = ref(false);
// 回复目标
const replyTarget = ref(null);
// 搜索关键词
const searchKeyword = ref("");
// 添加我的商品组件引用
const myProductsRef = ref(null);
const orderRef = ref(null);
const productData = ref(null);

// 添加显示我的商品状态
const showMyProducts = ref(false);
const showMyProductsList = ref(true);
const showOrder = ref(false);
// 分类数据
const categories = ref([
  { id: 0, name: "全部" },
  { id: 1, name: "数码" },
  { id: 2, name: "服装" },
  { id: 3, name: "书籍" },
  { id: 4, name: "生活" },
  { id: 5, name: "运动" },
  { id: 6, name: "其他" },
]);

// 当前选中的分类
const selectedCategory = ref(0);

// 排序选项
const sortOptions = ref([
  { value: "time", label: "最新" },
  { value: "price-asc", label: "价格升序" },
  { value: "price-desc", label: "价格降序" },
]);



// 检查用户登录状态
const checkLoginStatus = () => {
const userNickName = sessionStorage.getItem("userNickName");
const userId = sessionStorage.getItem("userId");

  if (userNickName && userId) {
    isLoggedIn.value = true;
    userName.value = userNickName;
  } else {
    isLoggedIn.value = false;
    userName.value = "";
  }
};

// 去登录页面
const goToLogin = () => {
  router.push("/login");
};


// 用户下拉菜单处理
const handleUserCommand = (command) => {
  switch (command) {
    case "myProducts":
      // 显示我的商品页面
      showMyProducts.value = true;
      showMyProductsList.value = false;
      showOrder.value = false;

      break;
    case "logout":
      handleLogout();
      break;
  }
};

// 退出登录
const handleLogout = () => {
  sessionStorage.removeItem("userNickName");
  sessionStorage.removeItem("userId");
  isLoggedIn.value = false;
  userName.value = "";
  ElMessage.success("已退出登录");
  // 页面刷新
  window.location.reload();
};

// 搜索处理
const handleSearch = () => {
  ElMessage.info(`搜索关键词: ${searchKeyword.value}`);
  loadProductList();
};

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId;
  loadProductList();
};

// 改变排序方式
const changeSort = (sortValue) => {
  selectedSort.value = sortValue;
  loadProductList();
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  loadProductList();
};

// 查看商品详情
const viewProductDetail = async (productId) => {
  if (!productId) {
    ElMessage.error("商品ID不能为空");
    return;
  }
  console.log("查看商品详情:", productId);
  try {
    // 获取商品详情
    const response = await instance.get(`/platform/get?id=${productId}`);
    if (response.data.code === 200) {
      currentProduct.value = response.data.data;
      drawerVisible.value = true;
      // 加载商品留言
      await loadProductReviews(productId);
      // 清空留言输入框
      newReviewContent.value = "";
    } else {
      ElMessage.error(response.data.message || "获取商品详情失败");
    }
  } catch (error) {
    console.error("获取商品详情出错:", error);
    ElMessage.error("获取商品详情失败，请稍后再试");
  }
};

// 联系卖家
const contactSeller = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning("请先登录后再联系卖家");
    return;
  }
  ElMessage.success("联系卖家功能已触发");
};
// 购买商品
const buyProduct = (productId) => {
  if (!isLoggedIn.value) {
    router.push("/login");
    return;
  }
  ElMessage.success(`购买商品功能已触发，商品ID: ${productId}`);
  showOrder.value = true;
  showMyProductsList.value = false;
  showMyProducts.value = false;
  drawerVisible.value = false;
  // 传递商品ID给订单组件
  productData.value = productId;
};

// 加载商品列表
const loadProductList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    // 如果有搜索关键词，则添加到参数中
    if (searchKeyword.value) {
      params.title = searchKeyword.value;
    }

    const response = await instance.get("/platform/list", { params });
    if (response.data.code === 200) {
      productList.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.message || "获取商品列表失败");
    }
  } catch (error) {
    console.error("获取商品列表出错:", error);
    ElMessage.error("获取商品列表失败，请稍后再试");
  }
};

// 获取完整图片URL
const getFullImageUrl = (imageUrl) => {
  // 如果有图片URL则直接返回，否则返回默认图片
  return imageUrl || "https://picsum.photos/300/300?random=1";
};

// 获取商品留言
const loadProductReviews = async (productId) => {
  try {
    const response = await instance.get(`/review/product/${productId}`);
    if (response.data.code === 200) {
      reviews.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || "获取商品留言失败");
    }
  } catch (error) {
    console.error("获取商品留言出错:", error);
    ElMessage.error("获取商品留言失败，请稍后再试");
  }
};

// 回复留言
const replyToReview = (review) => {
  console.log("回复留言:", review);
  replyTarget.value = review.id;
  newReviewContent.value = `@${review.userNickname} `;
};

// 取消回复
const cancelReply = () => {
  replyTarget.value = null;
  newReviewContent.value = "";
};

// 提交留言
const submitReview = async () => {
  if (!newReviewContent.value.trim()) {
    ElMessage.warning("请输入留言内容");
    return;
  }

  if (!isLoggedIn.value) {
    ElMessage.warning("请先登录后再发表留言");
    return;
  }

  const userId = sessionStorage.getItem("userId");
  if (!userId) {
    ElMessage.error("用户信息异常，请重新登录");
    return;
  }

  isSubmitting.value = true;
  try {
    const reviewData = {
      content: newReviewContent.value,
      userId: parseInt(userId),
      productId: currentProduct.value.id,
      parentId: replyTarget.value ? replyTarget.value.id : 0 // 如果是回复，则设置parentId
    };

    const response = await instance.post("/review/add", reviewData);
    if (response.data.code === 200) {
      ElMessage.success("留言发表成功");
      newReviewContent.value = "";
      replyTarget.value = null; // 清空回复目标
      // 重新加载留言列表
      await loadProductReviews(currentProduct.value.id);
    } else {
      ElMessage.error(response.data.message || "发表留言失败");
    }
  } catch (error) {
    console.error("发表留言出错:", error);
    ElMessage.error("发表留言失败，请稍后再试");
  } finally {
    isSubmitting.value = false;
  }
};

//监听sessionStorage变化
watch(() => sessionStorage.getItem("userNickName"), checkLoginStatus);

// 组件挂载时加载数据
onMounted(() => {
  checkLoginStatus();
  loadProductList();
});
</script>

<style scoped>
.platform-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.user-section {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.category-filter {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.category-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.category-scroll {
  width: 100%;
}

.category-list {
  display: flex;
  white-space: nowrap;
}

.category-item {
  padding: 8px 16px;
  margin-right: 10px;
  background-color: #f5f5f5;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-item:hover,
.category-item.active {
  background-color: #409eff;
  color: white;
}

.product-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sort-options .el-button {
  margin-right: 10px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 12px;
}

.product-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;

  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 18px;
  color: #ff4444;
  font-weight: bold;
  margin-bottom: 8px;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.product-detail {
  display: flex;
  height: auto;
  max-height: 60vh;
  overflow-y: auto;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
}

.detail-image {
  flex: 1;
  max-width: 40%;
  overflow: hidden;
  padding: 10px;
}

.carousel-image,
.single-image {
  width: 100%;
  max-height: 450px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-info {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  max-height: 60vh;
}

.detail-info h2 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  font-size: 22px;
}

.detail-price {
  font-size: 24px;
  color: #ff4444;
  font-weight: bold;
  margin-bottom: 15px;
}

.detail-condition,
.detail-description,
.detail-meta {
  margin-bottom: 12px;
}

.detail-meta div {
  margin-bottom: 6px;
  font-size: 14px;
}

.detail-meta .seller {
  font-weight: bold;
  color: #409eff;
}

.detail-meta .time,
.detail-meta .status,
.detail-meta .number,
.detail-meta .sold {
  color: #666;
}

.detail-description {
  color: #666;
  line-height: 1.5;
}

.detail-info .el-button {
  margin-right: 10px;
  margin-top: 10px;
}

/* 留言区域样式 - 图片式布局 */
.review-section {
  margin-top: 20px;
  padding: 15px;
  border-top: 1px solid #eee;
  max-height: 40vh;
  overflow-y: auto;
}

.review-section h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
}

.review-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 15px;
}

.review-item {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 15px;
  background-color: #fafafa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.review-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.review-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 2px solid #409eff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.review-user-info {
  flex: 1;
}

.review-nickname {
  font-weight: bold;
  color: #333;
  font-size: 15px;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  color: #666;
  line-height: 1.6;
  font-size: 14px;
  padding-left: 52px;
  background-color: white;
  padding: 10px;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.review-actions {
  margin-left: auto;
}

.reply-list {
  margin-top: 15px;
  padding-left: 30px;
  border-left: 2px dashed #dcdfe6;
}

.reply-item {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reply-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
  border: 1px solid #409eff;
}

.reply-user-info {
  flex: 1;
}

.reply-nickname {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-content {
  color: #666;
  line-height: 1.5;
  font-size: 13px;
  padding-left: 38px;
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
}

.review-form {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.review-form h4 {
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}

.login-prompt {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .product-detail {
    flex-direction: column;
    max-height: none;
  }

  .detail-image {
    max-width: 100%;
    margin-bottom: 20px;
  }

  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }

  .header {
    flex-direction: column;
    gap: 10px;
  }
  
  .detail-info {
    max-height: none;
  }
  
  .review-section {
    max-height: none;
  }
  
  .review-list {
    max-height: 350px;
  }
  
  .review-item {
    padding: 12px;
  }
  
  .reply-list {
    padding-left: 20px;
  }
  
  .detail-info .el-button {
    width: 100%;
    margin-bottom: 10px;
  }
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  background-color: #f5f5f5;
  padding: 10px 0;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

/* 为了防止footer遮挡内容，给页面主体添加底部边距 */
.full-height-container {
  padding-bottom: 50px; /* 根据footer高度调整 */
}
</style>